// (c) 2007 Messaging Logic. All Rights Reserved.
package org.xi8ix.jms;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import java.util.ArrayList;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Iain Shigeoka
 */
public class JMSDestination implements Destination {

    private static final Logger LOG = Logger.getLogger(JMSDestination.class.getName());
    private ArrayList<BlockingQueue<Message>> queues = new ArrayList<BlockingQueue<Message>>();
    private String name;

    public JMSDestination(String name) {
        this.name = name;
    }

    public void send(Message message) throws JMSException {
        LOG.log(Level.FINEST,"Sending message {0} to {1}",new Object[]{message,name});
        if (message instanceof JMSStreamMessage) {
            JMSStreamMessage streamMessage = (JMSStreamMessage) message;
            LOG.finest("stream message detected");
            streamMessage.reset();
            LOG.finest("Stream message reset");
            for (BlockingQueue<Message> queue: queues) {
                LOG.log(Level.FINEST,"Offering message to queue {0}",queue);
                queue.offer(new JMSStreamMessage(streamMessage));
                LOG.log(Level.FINEST,"Offered message to queue");
            }
        } else if (message instanceof JMSTextMessage) {
            JMSTextMessage textMessage = (JMSTextMessage) message;
            LOG.finest("Text message detected");
            for (BlockingQueue<Message> queue: queues) {
                LOG.log(Level.FINEST,"Offering message to queue {0}",queue);
                queue.offer(new JMSTextMessage(textMessage));
                LOG.log(Level.FINEST,"Offered message to queue");
            }
        } else if (message instanceof JMSMessage) {
            JMSMessage jmsMessage = (JMSMessage) message;
            LOG.finest("Base message detected");
            // todo MUST copy message objects
            for (BlockingQueue<Message> queue: queues) {
                LOG.log(Level.FINEST,"Offering message to queue {0}",queue);
                queue.offer(new JMSMessage(jmsMessage));
                LOG.log(Level.FINEST,"Offered message to queue");
            }
        } else {
            LOG.log(Level.WARNING, "Cannot send messages not created in this JMS system");
        }
    }

    public void add(BlockingQueue<Message> queue) {
        queues.add(queue);
        LOG.log(Level.FINEST,"Added queue {0} to {1}",new Object[]{queue,name});
    }

    public void remove(BlockingQueue<Message> queue) {
        queues.remove(queue);
        LOG.log(Level.FINEST,"Removed queue {0} from {1}",new Object[]{queue,name});
    }

    public String toString() {
        return super.toString() + ">" + name;
    }
}
